﻿namespace Jsl.FxCop
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Microsoft.VisualStudio.CodeAnalysis.Extensibility;

    [TestClass]
    public class TestRaiseEventsCorrectly
    {
        [TestMethod]
        public void Correctly_raise_event_is_OK()
        {
            var compiler = new CompileHelper()
                .AddSource(@"
using System;
public class Class
{
    private event EventHandler MyEvent;

    public void Method(EventArgs e)
    {
        var local = this.MyEvent;
        if (local != null)
        {
            local(this, e);
        }
    }
}");

            new CodeTestHelper(compiler)
                .Test(
                    (debugMode, method) =>
                    {
                        new RaiseEventsCorrectly()
                            .RunMethodRule(method)
                            .HasNoMoreProblems();
                    });
        }

        [TestMethod]
        public void Use_local_variable_to_raise_event()
        {
            var compiler = new CompileHelper()
                .AddSource(@"
using System;
public class Class
{
    private event EventHandler MyEvent;

    public void Method(EventArgs e)
    {
        if (this.MyEvent != null)
        {
            this.MyEvent(this, e);
        }
    }
}");

            new CodeTestHelper(compiler)
                .Test(false,
                    (method) =>
                    {
                        new RaiseEventsCorrectly()
                            .RunMethodRule(method)
                            .HasProblem(
                                90,
                                FixCategories.NonBreaking,
                                MessageLevel.Warning,
                                "Use a local variable to hold the raise the MyEvent event value. Check the local for null and raise the event from the local variable.")
                            .HasNoMoreProblems();
                    });
        }
    }
}